package com.zxh.baidu;

import com.zxh.util.Constant;
import com.zxh.util.HttpPoolUtil;
import com.zxh.audio.PlayUtil;
import com.zxh.util.ThreadPool;
import it.sauronsoftware.jave.AudioAttributes;
import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.EncoderException;
import it.sauronsoftware.jave.EncodingAttributes;
import org.apache.commons.io.FileUtils;
import org.apache.http.message.BasicNameValuePair;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * Created by zhangxh on 2016/7/11.
 */
public class TTSUtil {
    private static Logger logger=Logger.getLogger(TTSUtil.class);
    private static final String API_URI="http://tsn.baidu.com/text2audio";

    public static byte[] textToByte(String tex){
        logger.debug("请求语音合成:"+tex);
        byte[] retVytes= HttpPoolUtil.postRetMulti(API_URI, new BasicNameValuePair("tex", tex)
                , new BasicNameValuePair("cuid", Constant.getPropertity("cuid"))
                , new BasicNameValuePair("tok", BaiduUtil.getToken())
                , new BasicNameValuePair("lan", "zh")
                , new BasicNameValuePair("ctp", "1"));
        logger.debug("请求语音合成成功:"+tex);
        return retVytes;
    }

    public static File textToFile(String tex,String filePath,boolean toWav,Runnable...runnables){
        byte[] bytes=textToByte(tex);
        if(null!=bytes){
            File file=new File(filePath);
            try {
                FileUtils.writeByteArrayToFile(file,bytes);
                if(toWav){
                    changeToWav(file);
                }
                for(Runnable r:runnables){
                    ThreadPool.execute(r);
                }
                return file;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static void playText(String tex)  {
        String tempFilePath="sound" + File.separator + "tmp"+File.separator+System.currentTimeMillis()+".wav";
        File file=textToFile(tex, tempFilePath,true);
        try {
            PlayUtil.play(new FileInputStream(file));
            file.delete();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }
    private static void changeToWav(File file){
        Encoder encoder = new Encoder();
        EncodingAttributes attrs= new EncodingAttributes();
        AudioAttributes audio = new AudioAttributes();
//        	audio.setCodec("libmp3lame");
        audio.setBitRate(new Integer(8));
        audio.setChannels(new Integer(1));//单声道
//        	audio.setVolume(250);
        audio.setSamplingRate(new Integer(8000));
        attrs.setFormat("wav");
        attrs.setAudioAttributes(audio);
        try {
            encoder.encode(file,file,attrs);
        } catch (EncoderException e) {
            e.printStackTrace();
        }
    }


}
